<?php

require_once '../../bootstrap.php';
require_once '../entities/User.php';
require_once '../utils/util.php';

$user = new User();
session_start();
/*
 * Controlador correspondiente al login del usuario.
 */
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_SESSION['usuId'])) {
        //El usuario esta logueado.
        header('Location: ../referalPanel.php');
    } else {
        if (empty($_POST["user"]) || empty($_POST["pass"])) {
            $userErr = "User and Pass are required to login.";
            echo $userErr;
        } else {
            $userName = checkInput($_POST['user']);
            //Busco los campos del usuario en la base.
            $user = getUser($entityManager, $userName);

            if ($user === NULL) {
                //El usuario no existe;
                session_destroy();
                echo 'The user doesn\'t exist';
                exit();
            } else {
                // Verificar si la cuenta está habilitada.
                if ($user->getUsuEnable() !== 1) {

                    echo "The account is not enabled. Please check your mail.";
                    exit();
                }

                //Verificar si el pass es correcto.
                $pass = checkInput($_POST['pass']);
                if ($user->getUsuPass() === md5($pass)) {
                    // Login successfull
                    echo 'Login successfull';
                    //$_SESSION['usuId'] = $user->getUsuId();


                    /*                     * **************************** */
                    //¡La contraseña es correcta!
                    $user_browser = $_SERVER['HTTP_USER_AGENT']; //Obtén el agente de usuario del usuario
                    $user_id = preg_replace("/[^0-9]+/", "", $user->getUsuId()); //protección XSS ya que podemos imprimir este valor
                    $_SESSION['usuId'] = $user_id;
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $user->getUsuUser()); //protección XSS ya que podemos imprimir este valor
                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512', $pass . $user_browser);
                    //Inicio de sesión exitosa
                    //return true;
                    /*                     * **************************** */

                    header('Location: ../referalPanel.php');
                } else {
                    // La pass está mal;
                    session_destroy();
                    echo 'The pass is wrong!';
                    //header('Location: ../login.php');
                    exit();
                }
            }
        }
    }
} else {
    die();
    header('Location: ../src/index.php');
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Inicio de session.
//session_destroy();
}

function getUser($entityManager, $userName) {
    $userData = $entityManager->getRepository('User')->findOneBy(array('usuUser' => $userName));
    return $userData;
}
